const requireDirectory = require("require-directory");
const Router = require('koa-router')

class InitManager {
    static initCore(app){
        InitManager.app =app
        InitManager.initLoadRouters()
        InitManager.loadHttpException()
        InitManager.loadConfig()
    }
    // 自动注册API路由模块
    static initLoadRouters(){
        const apiDirectory = `${process.cwd()}/app/api`
        requireDirectory(module,apiDirectory,{
            visit:whenLoadModule
        })

        function whenLoadModule(obj){
            if (obj instanceof Router) {
                InitManager.app.use(obj.routes())
            }
        }
    }
    // 把异常处理挂载到全局global上
    static loadHttpException(){
        const errors = require('./httpException')
        global.errs = errors
    }
    // 判断环境
    static loadConfig(path=''){
        const configPath = path || process.cwd()+'/config/config.js'
        const config = require(configPath)
        global.config = config
    }
}

module.exports = InitManager